import axios from "axios"
import type { AxiosResponse, InternalAxiosRequestConfig } from "axios"
import { cloneDeep } from 'lodash-es'
import { useAppStore } from '@/stores'
import { transInterceptors } from './transInterceptors'
const { handleResponse, handleRequest, handleResponseError } = transInterceptors()
import { axiosCancel } from './helper'

export function createAxios (options) {
  let opts = cloneDeep(options)
  const instance = axios.create(opts)

  const axiosCanceler = new axiosCancel()

  // 请求拦截器
  instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
    const { ignoreRepeatRequest = false } = opts

    ignoreRepeatRequest && axiosCanceler.addCancel(config)

    // 在发送请求之前做些什么
    return handleRequest(options, config)
  }, error => {
    // 对请求错误做些什么
    return Promise.reject(error)
  })

// 响应拦截器
  instance.interceptors.response.use((response: AxiosResponse) => {
    // 对响应数据做点什么
    return handleResponse(options, response)
  }, error => {
    // 对请求错误做些什么
    return handleResponseError(options, error)
  })

  const { saveAxiosInstance } = useAppStore()

  saveAxiosInstance(cloneDeep(instance))

}

